﻿using B.S.DataBase.SuYuan.Domains.Entites;
using B.S.DataBase.SuYuan.ErrorCode;
using B.S.DataBase.SuYuan.Infrastructure.Interfaces;
using B.S.DataBase.SuYuan.Read.API.Applications.Commands.Shop;
using B.S.DataBase.SuYuan.Read.API.Dtos;
using MediatR;

namespace B.S.DataBase.SuYuan.Read.API.Applications.CommandHandlers.Shop
{
    public class ShopInfoQueryCommandHandler : IRequestHandler<ShopInfoQueryCommand, APIPaning<ShopInfoDto>>
    {
        private readonly IBaseRepository<ShopInfoModel> sRepo;
        private readonly IBaseRepository<ShopTypeModel> tRepo;

        public ShopInfoQueryCommandHandler(IBaseRepository<ShopInfoModel> sRepo, IBaseRepository<ShopTypeModel> tRepo)
        {
            this.sRepo = sRepo;
            this.tRepo = tRepo;
        }


        public Task<APIPaning<ShopInfoDto>> Handle(ShopInfoQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaning<ShopInfoDto> result = new APIPaning<ShopInfoDto>();
            result.Code = ResultCode.查询成功;
            result.Msg = ResultCode.查询成功.ToString();
            var list = from a in sRepo.GetAll()
                       join b in tRepo.GetAll() on a.ShopTypeId equals b.ShopTypeId
                       where a.IsDel == false
                       select new ShopInfoDto
                       {
                           ShopId = a.ShopId,
                           ShopTypeId = a.ShopTypeId,
                           BatchId = a.BatchId,
                           BaaoZhiQi = a.BaaoZhiQi,
                           Productionnumber = a.Productionnumber,
                           Manufacturers = a.Manufacturers,
                           FengMian = a.FengMian,
                           WanShanDu = a.WanShanDu,
                           ImgId = a.ImgId,
                           IsDel = a.IsDel,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           ShopName = b.ShopName,
                       };
            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.ShopId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            result.TotalCount = TotalCount;
            result.TotalPage = TotalPage;
            result.List = list.ToList();
            return Task.FromResult(result);



        }
    }
}
